<?php
/**
 * @package PWE.modele
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_page extends modele_publication {
    protected static $_table = 'publication';
    protected $_discriminant = 'page';
    public $type = 'page';
    
    private $_internal_category = null;
    
    public function isPage(){
        return true;
    }
    
    /**
     * renvoi la catégorie de construction de la page
     * @return \modele_category
     */
    public function getInternalCategory(){
        if($this->_internal_category===null){
            $this->_internal_category = ($this->getInternalCategoryId()>0)?new modele_category($this->getInternalCategoryId()):new modele_category();
        }
        return $this->_internal_category;
    }
    /**
     * renvoi l'identifiant de la catégorie de construction de la page
     * @return int
     */
    public function getInternalCategoryId(){
        return parent::getCategoryId();
    }
    /**
     * renvoi la categorie parent de la page
     * @return \modele_category
     */
    public function getCategory() {
        return ($this->getInternalCategory()!==null)?$this->getInternalCategory()->getParent():null;
    }
    /**
     * renvoi l'identifiant de la catégory parent
     * @return int
     */
    public function getCategoryId() {
        return ($this->getCategory()!==null)?$this->getCategory()->getCategoryId():0;
    }
    /**
     * indique si la page a un parent
     * @return boolean
     */
    public function haveParent(){
        return $this->getInternalCategory()->haveParent();
    }
    /**
     * renvoi l'id du parent
     * @return int
     */
    public function getParentId(){
        return ($this->haveParent())?$this->getInternalCategory()->getParentId():0;
    }
    /**
     * renvoi la category parent
     * @return \modele_category
     */
    public function getParent(){
        return ($this->haveParent())?$this->getInternalCategory()->getParent():null;
    }
    /**
     * indique si la page a des element enfants
     * @return boolean
     */
    public function haveChild(){
        return ($this->getInternalCategory()!==null)?$this->getInternalCategory()->haveChild():false;
    }
    /**
     * renvoi une liste de modele enfant
     * @return array
     */
    public function getChild(){
        return ($this->haveChild())?$this->getInternalCategory()->getChild():array();
    }
    
    /**
     * renvoi le template de page
     * @return string
     */
    public function getTemplate(){
        return $this->getInternalCategory()->getTemplate();
    }
        
    public function getUrl(){
        $urlCategory = ($this->getInternalCategory()!==null)?$this->getInternalCategory()->getUrl():PWE::getBaseURL();
        $urlCategory = (substr($urlCategory,-1)==='/')?substr($urlCategory, 0,-1):$urlCategory;
        $lienCategory = ($this->getInternalCategory()!==null)?$this->getInternalCategory()->getPermalien()->getCleanedLien(true):'';
        
        $url = str_replace($lienCategory, '', $urlCategory).$this->getPermalien()->getLien();
        return $url;
    }
    public function getTranslatedUrl($lang=''){
        $urlCategory = ($this->getInternalCategory()!==null)?$this->getInternalCategory()->getTranslatedUrl($lang):PWE::getBaseURL();
        $urlCategory = (substr($urlCategory,-1)==='/')?substr($urlCategory, 0,-1):$urlCategory;
        $lienCategory = ($this->getInternalCategory()!==null)?$this->getInternalCategory()->getPermalien()->getCleanedTranslatedLien($lang,true):'';
        
        $url = str_replace($lienCategory, '', $urlCategory).$this->getPermalien()->getTranslatedLien($lang);
        return $url;
    }
    
    public function getNombrePublications($public=false){
        return 1;
    }
    public function getPublications($public=false){
        return array($this);
    }
    
    public function getDatas($input=false){
        $datas = parent::getDatas($input);
        $datas['category_id'] = $this->getInternalCategoryId();
        $datas['parent_id']= $this->getParentId();
        $datas['modele']= "page";
        return $datas;
    }
    
    public function setOrder($order){
        $this->getInternalCategory()->setOrder($order);
        parent::setOrder($order);
    }
    
    public function setDatas($datas) {
        $datasCategory = $datas;
        $datasCategory['_discriminant'] = 'page';
        if($this->getInternalCategory()->getId()>0){
            unset($datasCategory['_lien']);
            unset($datasCategory['lien']);
        }
        $this->getInternalCategory()->setDatas($datasCategory);
        
        return parent::setDatas($datas);
    }
    
    public function save() {
        $this->getInternalCategory()->save();
        $categoryId = $this->getInternalCategory()->getId();
        //post
        $this->getPost()->save();
        $postId = $this->getPost()->getId();
        if($postId>0){
           //publication
           $sqlQuery = 'INSERT INTO '.self::getTable().' ';
           $sqlQuery .= '(date,statut_id,post_id,category_id,type_id,template,order_idx) ';
           $sqlQuery .= 'VALUES ("'.$this->getDate().'",'.$this->getStatutId().','.$postId.','.$categoryId.','.$this->getTypeId().',"'.$this->getTemplate().'",'.$this->getOrder().')';
           
           bdd_sql::doSql($sqlQuery,false);
           $this->setId(bdd_sql::getLastInsertId());

           if($this->getId()>0){
               //permalien
               $this->getPermalien()->setDatas(array('_modele_id'=>$this->getId()));
               $this->getPermalien()->save();

               return array('success'=>true,'datas'=>$this->getDatas());
           }else{
               $this->getInternalCategory()->delete();
               $this->getPost()->delete();
               return array('success'=>false,'datas'=>array());
           }
        }else{
            $this->getInternalCategory()->delete();
            return array('success'=>false,'datas'=>array());
        }
    }
    public function update() {
        $this->getInternalCategory()->update();
        //post
        $this->getPost()->update();
        //publication
        $sqlQueryPublication = 'UPDATE '.self::getTable().' SET ';
        $sqlQueryPublication .= 'date="'.$this->getDate().'",';
        $sqlQueryPublication .= 'category_id='.$this->getInternalCategoryId().', ';
        $sqlQueryPublication .= 'type_id='.$this->getTypeId().', ';
        $sqlQueryPublication .= 'statut_id='.$this->getStatutId().', ';
        $sqlQueryPublication .= 'media_id='.$this->getMediaId().', ';
        $sqlQueryPublication .= 'order_idx='.$this->getOrder().', ';
        $sqlQueryPublication .= 'is_deleted='.$this->getIsDeleted().', ';
        $sqlQueryPublication .= 'template="'.$this->getTemplate().'" ';
        $sqlQueryPublication .= 'WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQueryPublication,false);
        
        //permalien
        $this->getPermalien()->update();

        return array('success'=>true,'datas'=>$this->getDatas());
    }
    public function delete() {
        $retour = parent::delete();
        $this->getInternalCategory()->delete();

        return $retour;
    }

    /* methodes statiques */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    
    /**
     * 
     * @param int $start
     * @param int $type_id
     * @return array \modele_page
     */
    public static function getListe($start = 0,$type_id = 1){
        $sqlQuery = 'SELECT p.id AS id FROM '.self::getTable().' AS p LEFT JOIN '.modele_category::getTable().' AS c ON c.id=p.category_id WHERE p.is_deleted = 0 AND p.type_id='.$type_id.' AND c.discriminant="page" ORDER BY c.order_idx, p.category_id, p.date DESC';
        if($start>0){
            $sqlQuery .=  ''; // TODO pagination
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        
        if($results['count']>0){
            foreach($results['results'] as $pageData ){
                $retour[] = new modele_page($pageData['id']);
            }
        }
        
        return $retour;
    }
    /**
     * renvoi la liste des pages de premier niveau => sans parent
     * @param int $start
     * @param int $limit
     * @return \modele_page
     */
    public static function getPrimaryListe($start=0,$limit=0){
        $sqlQuery = 'SELECT p.id AS id FROM '.self::getTable().' AS p LEFT JOIN '.modele_category::getTable().' AS c ON c.id=p.category_id WHERE p.is_deleted = 0 AND c.discriminant="page" AND c.parent_id IS NULL ORDER BY c.order_idx, p.category_id, p.date DESC';
        if($start>0){
            $sqlQuery .=  ' LIMIT '.$start.','.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $pageData ){
                $retour[] = new modele_page($pageData['id']);
            }
        }
        return $retour;
    }
}
?>